var zTree;
var treeObj;
var roleForm;
$(function () {
    var columns = [
        {
            checkbox: true
        }, {
            field: 'name',
            title: '名称'
        }, {
            field: 'remarks',
            title: '备注'
        },
        {
            field: 'createDate',
            title: '创建时间',
            formatter: function (value, row, index) {
                return changeDateFormat("yyyy-MM-dd hh:mm:ss", new Date(value))
            }
        }, {
            field: 'id',
            title: '操作',
            formatter: function (value, row, index) {
                return '<button id="btn_edit" type="button" class="btn btn-primary  btn-xs" onclick="update(\'' + value + '\')"><i class="fa fa-edit"></i>修改</button>' +
                    '<button type="button" class="btn btn-danger  btn-xs" onclick="deletes(\'' + value + '\')" style="margin-left: 10px;"><i class="fa fa-trash-o"></i> 删除</button>';
            }
        }
    ]
    createBootstrapTable($("#table"), '/sys/sysRole/info', columns, true, 'toolbar', 'server')

    var setting = {
        check: {
            enable: true,
            chkStyle: "checkbox",
            chkboxType: {
                "Y": "ps",
                "N": "s"
            }
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: null
            }
        },
        callback: {
            beforeCheck: true,
            onCheck: onCheck
        }
    };

    request('/sys/sysMenu/zTreeNodes', 0, null, function (data) {
        if (data.code == 1) {
            zTree = $.fn.zTree.init($("#typeTree"), setting, data.data);
            treeObj = $.fn.zTree.getZTreeObj("typeTree");
            treeObj.expandAll(true);
        } else {
            layer.msg("树表初始化失败！")
        }
    }, function (error) {
        layer.msg("系统异常！")
    })
})

// 清空表单
function resetForm() {
    $("#name").val("")
    $("#roleId").val("")
    $("#mids").val("")
    $("#remarks").val("")
}

//树形菜单选中事件
function onCheck(e, treeId, treeNode) {
    var ckid = []
    var nodes = treeObj.getCheckedNodes(true)
    for (var n in nodes) {
        ckid.push(nodes[n].id)
    }
    $("#mids").val(ckid)
}


function doSetSelectNode(ids) {
    var treeObj = $.fn.zTree.getZTreeObj("typeTree")
    //取消所有选中等待重新赋值
    treeObj.checkAllNodes(false);
    for (var i = 0; i < ids.length; i++) {
        var node = treeObj.getNodeByParam("id", ids[i]);
        if (node != null || node != undefined)
        node.checked = true
    }
    // 刷新节点状态
    treeObj.refresh()
}

//新增
function add() {
    resetForm()
    roleForm = layer.open({
        type: 1,
        area: (window.innerWidth>992)? "600px":"auto",
        title: '新增',
        shade: 0.6,
        maxmin: false,
        anim: 1,
        content: $("#role_form"),
        success: function (layero, index) {
            layer.iframeAuto(index);
        }
    });
}

function save() {
    var id = $("#roleId").val()
    var name = $("#name").val();
    var remarks = $("#remarks").val();
    var mids = $("#mids").val();
    if (name == '' || name == null) {
        layer.msg("请输入名称！")
        return
    }
    if (mids == '' || mids == null) {
        layer.msg("请选择要分配的权限！")
        return
    }

    var data = {
        id: id,
        name: name,
        remarks: remarks,
        mids: mids
    }

    request('/sys/sysRole/save', 1, data, function (res) {
        if (res.code == 0) {
            layer.close(roleForm)
            layer.msg(res.msg, {time: 1000}, function () {
                onLoads($("#href").val())
            })
        } else {
            layer.msg(res.msg, {time: 1000})
        }
    }, function (error) {
        layer.msg("系统异常！")
    })
}

/**
 * 修改
 */
function update(id) {
    resetForm()
    var data = {
        id: id
    }
    request('/sys/sysRole/update', 0, data, function (res) {
        if (res.code == 0) {
            $("#name").val(res.data.role.name)
            $("#roleId").val(res.data.role.id)
            $("#mids").val(res.data.ids)
            $("#remarks").val(res.data.role.remarks)
            doSetSelectNode(res.data.ids)
        } else {
            layer.msg(res.msg, {icon: 5})
        }
    }, function (error) {
        layer.msg("系统异常！", {icon: 5})
    })

    roleForm = layer.open({
        type: 1,
        area: (window.innerWidth>992)? "600px":"auto",
        title: '修改',
        shade: 0.6,
        maxmin: false,
        anim: 1,
        content: $("#role_form"),
        success: function (layero, index) {
            layer.iframeAuto(index);
        }
    });
}

function deletes(id) {

    var ids = [];
    if (id != undefined) {
        ids.push(id)
    } else {
        $.each($('tbody input:checkbox:checked'), function () {
            ids.push($(this).parents('tr').data('uniqueid'));
        });
    }

    if (ids.length < 1) {
        layer.msg("最少请选择一条数据！")
        return;
    }

    var data = {
        ids: ids.toString()
    }

    layer.confirm('确定删除吗？', {
        title:'提示',btn: ['取消', '确定']
    }, function () {
        layer.close(layer.index)
    }, function () {
        request('/sys/sysRole/delete', 0, data, function (res) {
            if (res.code == 0) {
                layer.msg("删除成功", {time: 1000}, function () {
                    onLoads($("#href").val())
                })
            }else {
                layer.msg(res.msg, {time: 1000})
            }
        }, function (error) {
            layer.msg("系统异常！")
        })
    });
}


function searchForm() {
    var searchName = $("#searchName").val()

    var data = {
        name: searchName
    }

    request('/sys/sysRole/info', 1, data, function (res) {
        $("#table").bootstrapTable('load', res);
    }, function (error) {
        layer.msg(error.msg)
    })
}

function restForm() {
    request('/sys/sysRole/info', 1, null, function (res) {
        $("#table").bootstrapTable('load', res);
    }, function (error) {
        layer.msg(error.msg)
    })
}

